package com.gz.qqserveer;

import com.gz.common.Message;
import com.gz.common.MessageType;
import com.gz.utilis.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

public class SendNewsToAll implements Runnable {

    @Override
    public void run() {
        while(true){
            System.out.println("请输入服务器要推送的新闻/消息(退出输入exit): ");
            String news= Utility.readString(100);
            if(news.equals("exit")){
                break;
            }
            Message message = new Message();
            message.setContent(news);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formatedDate = simpleDateFormat.format(new Date());
            message.setSendTime(formatedDate);
            message.setMestype(MessageType.MESSAGE_SER_NEWS);

            HashMap<String,ServerConnectClientThread> hashMap=MangeServerConnectClientThread.getHashMap();
            Iterator<String> iterator=hashMap.keySet().iterator();
            while(iterator.hasNext()){//遍历客户端socket，给除了发送端的在线用户发送群发消息
                String userId=iterator.next();
                if(!userId.equals(message.getSender())){
                    try {
                        ObjectOutputStream oops = new ObjectOutputStream(hashMap.get(userId).getSocket().getOutputStream());
                        oops.writeObject(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
